import './index.scss';
import React, { useCallback, useMemo, useState, useEffect } from 'react';
import MyCheckbox from '../MyCheckbox';
import MyButton from '../MyButton';

function MyCheckboxList(props) {
  const { data, headerCells, allCheckedTip, onCheckedDataChange } = props;

  const [checkedData, setCheckedData] = useState([]);
  const [originData, setOriginData] = useState(data);

  //全选逻辑：依赖checkedData有发生更改时才去重新计算
  const allCheckedText = useMemo(() => {
    if (checkedData.length >= 0 && checkedData.length < originData.length) {
      //显示全选
      return allCheckedTip.all || 'Check all';
    } else {
      //显示全部撤销
      return allCheckedTip.none || 'Cancel all';
    }
  }, [checkedData]);

  //拿到data数组某一项里面的属性名
  //[{id:1, name:'xxx', score: 69}] -> id name score
  const dataProps = Object.keys(originData[0]);

  //设置全选
  const setAllCheck = useCallback((e) => {
    const _checked = e.target.checked;
    setCheckedData(_checked ? originData : []);
  });

  //设置单选
  const setSingleCheck = useCallback((e, item) => {
    const _checked = e.target.checked;

    //如果为真，新增一项
    //如果为假，删除一项
    setCheckedData((checkedData) =>
      _checked
        ? [...checkedData, item]
        : checkedData.filter((data) => data.id !== item.id)
    );
  });

  //点击删除某一项
  const removeItem = useCallback((id) => {
    setOriginData((originData) => originData.filter((item) => item.id !== id));
    setCheckedData((checkedData) =>
      checkedData.filter((item) => item.id !== id)
    );
  });

  //依赖项checkedData有更改时执行程序
  useEffect(() => {
    onCheckedDataChange(checkedData);
  }, [checkedData]);

  return (
    <div>
      <table border="1" width="500" align="center">
        <thead>
          <tr>
            <td colSpan={5} align="left">
              <MyCheckbox
                checked={checkedData.length === originData.length}
                onChange={(e) => setAllCheck(e)}
              >
                {allCheckedText}
              </MyCheckbox>
            </td>
          </tr>
          {/* tr根据headerCells存在才去渲染 */}
          {headerCells && (
            <tr>
              {headerCells.map((item) => (
                <th key={item}>{item}</th>
              ))}
            </tr>
          )}
        </thead>
        <tbody>
          {originData &&
            originData.map((item) => (
              <tr key={item.id}>
                <td>
                  {/* checked：找到某项就选中 */}
                  <MyCheckbox
                    checked={checkedData.some((data) => data.id === item.id)}
                    onChange={(e) => setSingleCheck(e, item)}
                  ></MyCheckbox>
                </td>
                {/* ['id', 'name', 'score'] */}
                {dataProps.map((prop) => (
                  <td key={prop}>{item[prop]}</td>
                ))}
                <td>
                  <MyButton type="danger" onClick={() => removeItem(item.id)}>
                    删除
                  </MyButton>
                </td>
              </tr>
            ))}
        </tbody>
      </table>
    </div>
  );
}

export default MyCheckboxList;
